import { director, game, Node } from "cc";
import { asapScheduler, asyncScheduler, interval, timer, startWith, map } from "../../rxjs";
import { Observable } from "../internal/Observable";
import { nodeScheduler, sceneScheduler } from "./schedule/creator";

// 时间段单位为毫秒

// 本帧，尽快发出 （跟creator无关）
export function Asap(): Observable<number> {
    return timer(0, asapScheduler)
}

// 本帧，异步发出（跟creator无关）
export function Async(): Observable<number> {
    return timer(0, asyncScheduler);
}

// 下一帧发出
export function NextFrame(): Observable<number> {
    return timer(0, sceneScheduler);
}

export function EveryFrame() {
    return IntervalStartNow(0).pipe(map(_ => game.deltaTime));
}

// due毫秒后发出或到达指定时间后发出
export function Timer(due: number | Date, obj?: Node): Observable<number> {
    if (typeof due == 'number') due *= 1000;
    if (obj == null) {
        return timer(due, sceneScheduler);
    }
    return timer(due, nodeScheduler(obj));
}

// period周期循环调用
export function Interval(period, obj?: Node): Observable<number> {
    const scheduler = obj == null ? sceneScheduler : nodeScheduler(obj);
    return interval(period * 1000, scheduler);
}

// 与Interval相同，不过是第一次立即开始
export function IntervalStartNow(period, obj?: Node): Observable<number> {
    return Interval(period, obj).pipe(startWith(-1), map(_ => _ + 1));
}